package sk.openit.hibernate.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import org.apache.log4j.BasicConfigurator;

import sk.openit.hibernate.entities.Address;
import sk.openit.hibernate.entities.Person;

public class RunApp {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		BasicConfigurator.configure();
	       // Create the EntityManager
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa-hibernate");
        EntityManager em = emf.createEntityManager();
        
        //persist ------------------------------------------------------------------------
//        em.getTransaction().begin();
//        Address address = new Address(null, "Lublanska 3", "Zilina", "01008", null);
//        em.persist(address);
//        em.getTransaction().commit();

        //find  ---------------------------------------------------------------------------
        Address myAddress = em.find(Address.class, 12);
        System.out.println(myAddress);

//        em.getTransaction().begin();
//        myAddress.setZipCode("84444");
//        em.getTransaction().commit();
        
        //query ---------------------------------------------------------------------------
        Query query1 = em.createQuery("select a from Address a");
        List<Address> addresses1 = query1.getResultList();
        System.out.println(addresses1.size());
        for (Address address : addresses1) {
			System.out.println(address);
		}
        
        //named query ---------------------------------------------------------------------
        Query query2 = em.createNamedQuery("Address.findAll");
        List<Address> addresses2 = query2.getResultList();
        System.out.println(addresses2.size());
        for (Address address : addresses2) {
			System.out.println(address);
			for (Person person : address.getPersons()) {
				System.out.println(" - " + person);
			}
			
		}

        //named query with parameters -----------------------------------------------------
        Query query3 = em.createNamedQuery("Address.findByZipCode");
        List<Address> addresses3 = query3.setParameter("zipCode", "01008").getResultList();
        System.out.println(addresses3.size());
        for (Address address : addresses3) {
			System.out.println(address);
		}

        em.close();
        emf.close();
	}

}
